<?php
/**
 *
 * @author dawei
 * @copyright 139.com Inc
 */

class ApiUtility
{
    /**
     * 消除filter影响
     */
    static public function StripFilter ()
    {
        foreach ($_SERVER as $key => $val) {
            $_SERVER["$key"] = filter_input(INPUT_SERVER, $key, 
            FILTER_UNSAFE_RAW);
        }
        foreach ($_POST as $key => $val) {
            $_POST["$key"] = filter_input(INPUT_POST, $key, FILTER_UNSAFE_RAW);
        }
        foreach ($_GET as $key => $val) {
            $_GET["$key"] = filter_input(INPUT_GET, $key, FILTER_UNSAFE_RAW);
        }
    }

    static public function urlencode_rfc3986 ($input)
    {
        if (is_array($input)) {
            return array_map(array('ApiUtility', 'urlencode_rfc3986'), $input);
        } else 
            if (is_scalar($input)) {
                return str_replace('+', ' ', 
                str_replace('%7E', '~', rawurlencode($input)));
            } else {
                return '';
            }
    }

    /**
     * generate curl postfield
     * @param array $post_data
     */
    static public function generate_postfield ($post_data)
    {
        $post_data_str = '';
        foreach ($post_data as $k => $v) {
            $post_data_str .= '&' . $k . '=' . urlencode($v);
        }
        $post_data_str = substr($post_data_str, 1);
        return $post_data_str;
    }

    /*
     * generate multi-part curl postfield
     */
	public static function generate_postfield_multi($params, $boundary) {
		if (!$params) return '';

		uksort($params, 'strcmp');

		$pairs = array();

		$MPboundary = '--'.$boundary;
		$endMPboundary = $MPboundary. '--';
		$multipartbody = '';

		foreach ($params as $parameter => $value) {

			if( in_array($parameter, array('pic'))) {
				$url = $value['path'];
				$filename = $value['name'];
				$content = file_get_contents( $url );

				$multipartbody .= $MPboundary . "\r\n";
				$multipartbody .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"'. "\r\n";
				$multipartbody .= "Content-Type: image/unknown\r\n\r\n";
				$multipartbody .= $content. "\r\n";
			} else {
				$multipartbody .= $MPboundary . "\r\n";
				$multipartbody .= 'content-disposition: form-data; name="' . $parameter . "\"\r\n\r\n";
				$multipartbody .= $value."\r\n";
			}
		}

		$multipartbody .= $endMPboundary;
		return $multipartbody;
	} 

    /**
     * 用于给array_walk_recursive给array的值递归进行urlencode
     * 
     * @param mixed $item
     * @param mixed $key
     */
	static function rUrlencode(&$item, $key) {
		$item = urlencode($item);
	}

	/**
	 * 获取客户端IP地址
	 *
	 * @param unknown_type $is_strip
	 * @param unknown_type $default
	 */
    static public function GetRemoteIp ($is_strip=false, $default='')
    {
        $ip = explode(',', getenv('HTTP_X_FORWARDED_FOR') . ',' . getenv('REMOTE_ADDR') . ',' .getenv('HTTP_CLIENT_IP'));
        foreach ($ip as $v) {
            if ($is_strip && in_array(substr($v, 0, 3), array('10.', '127', '172', '192', '224', '010')))
                continue;
            if (preg_match('/\d+\.\d+\.\d+\.\d+/', $v, $matches))
                return $matches[0];
        }
        if ($is_strip)
            return $default;
        else
            return '127.0.0.1';
    }

    /**
     * 计时器(返回当前的微秒数)
     * 
     */
    static public function timer ()
    {
        list ($usec, $sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
	}

	static public function generateKey ( $unique = false ) {
		$key = md5(uniqid(rand(), true));
		if($unique) {
			list($usec,$sec) = explode(' ',microtime());
			$key .= dechex($usec).dechex($sec);
		}
		return $key;
	}
	
	/**
	 *获取请求的url
	 *
	 */
	static function GetBaseUri() {
		$baseuri = isset($_SERVER['SCRIPT_URI']) ?
		$_SERVER['SCRIPT_URI'] :
		'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
		return $baseuri;
	}

}
